package org.ting.book.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ting.book.component.ResultFail;
import org.ting.book.component.ResultGenerator;
import org.ting.book.component.ResultSuccess;
import org.ting.book.constants.Constants;
import org.ting.book.mapper.UserMapper;
import org.ting.book.model.Result;
import org.ting.book.model.UserInfo;
import org.ting.book.utils.JwtUtils;

import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    ResultGenerator success = new ResultSuccess();
    ResultGenerator fail = new ResultFail();
    public Result<?> login(String userName, String password) {
        UserInfo userInfo = userMapper.getUserInfoByName(userName);
        try {
            if (userInfo == null) {
                throw new LoginException("用户名不存在");
              //  return fail.getResult("用户名不存在");
            }
            if (!userInfo.getPassword().equals(password)) {
                throw new LoginException("密码错误");
              //  return fail.getResult("密码错误");
            }
        }catch (LoginException e) {
            return fail.getResult(e.getMessage());
        }
        //生成token
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID, userInfo.getId());
        claim.put(Constants.TOKEN_IS_ADMIN, userInfo.getIsAdmin());
        return success.getResult(JwtUtils.genJwtToken(claim));
    }

    public Result<?> signUp(String userName, String password) {
        if(userMapper.getUserInfoByName(userName) != null) {
            return fail.getResult("用户已注册");
        }
        //存入数据库
        Integer result = userMapper.insert(userName, password);

        if(result == 1) {
            return success.getResult();
        }
        return fail.getResult();
    }

    public Result<?> restPassword(String userName, String password) {
        UserInfo userInfo = userMapper.getUserInfoByName(userName);
        userInfo.setPassword(password);
        Integer result = userMapper.update(userInfo);
        if(result == 1) {
            return success.getResult();
        }
        return fail.getResult();
    }

    public UserInfo getUserById(Integer idInToken) {
        return userMapper.getUserInfoById(idInToken);
    }

    public Result<?> adminSignUp(Integer userId, String code) {
        if(!code.equals("1234")) {
            return fail.getResult("认证码错误");
        }
        UserInfo userInfo = userMapper.getUserInfoById(userId);
        if(userInfo.getIsAdmin()) {
            return fail.getResult("该用户已是管理员");
        }
        userInfo.setIsAdmin(true);
        if(userMapper.update(userInfo) == 1) {
            return success.getResult();
        }
        return fail.getResult();
    }
}
